import axios from 'axios'
import { error } from '../utils/toast'
import { getItem, removeItem } from '../utils/save'
import router from '../router'

// 创建实例时设置配置的默认值
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 1000 * 3600 * 5,
  withCredentials: true // 允许添加cookie
})

// 添加响应拦截器
service.interceptors.response.use(res => {
    const { data } = res

    if (!data) {
      error("==response==", res.data.message)
    }
    return res.data
}, err => {
  return Promise.reject(err)
})

/**
* 统一发送请求
*  config 请求参数
*/

function isLogin(url) {
  if (url.includes("/login") || url.includes("/qrcode_bind")) {
    return true
  }
  return false
}

export function request(config) { 
    // for (const i in config.data) {
    //     if (!config.data[i] && config.data[i] !== 0 && config.data[i] !== false) delete config.data[i]
    // }
    const user_id = getItem('user_info') ? getItem('user_info').user_id : 0
    /* 考虑ie浏览器强大缓存问题，接口链接添加时间戳_t */
    const nowTime = Date.parse(new Date()) / 1000
    // 本地mock情况下取testUrl字段 统一使用location.origin

    if (config['baseUrl']) {
        config['url'] = config['baseUrl'] + config['url']
    } 

    console.log("--------request------------",  config)
    if (!getItem('user_info') && !isLogin(config.url)) {
        removeItem('user_info')
        router.push({ path: '/login' })
        return
    }

    // config['headers'] = {'Content-Type': 'audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3'}
    // get请求时替换掉 字段data 为params

    if (config['method'].toLowerCase() === 'get') {
        config['params'] = { ...config['data'], _t: nowTime, userid: user_id }
        delete config['data']
    } else {
        if (config['url'].includes('?')) {
          config['url'] += ('&_t=' + nowTime)
        } else {
          config['url'] += ('?_t=' + nowTime)
        }
        if (!isLogin(config.url)) {
          config.url += ('&userid=' + user_id)
        }
    }

    return service(config)
}